package com.example.demo.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.example.demo.core.DefineConstant;

/**
 * @title:	TerminalUtil
 * @author:	许子文
 * @date:	2019年6月28日 
 * @descirption: 终端工具类
 */
public class TerminalUtil {
	private static Logger logger = LoggerFactory.getLogger(TerminalUtil.class);
	
	/**
	 * @title executeCommand
	 * @author: 许子文
	 * @date: 2019年6月28日
	 * @description: 使用终端窗口执行命令
	 * @return 如果返回字符串以SUCCESS开头说明执行成功  如果返回字符串以ERROR开头说明执行失败
	 */
	public static String executeCommand(String command){
		
		String[] cmd = null;
		
		if(OSUtil.getOSName().startsWith(DefineConstant.WINDOWSOS)) {
			cmd = new String[] {"cmd","/c",command};
		}else if(OSUtil.getOSName().startsWith(DefineConstant.LINUXOS)) {
			cmd = new String[] {"sh","-c",command};
		}
		
		Runtime runtime = Runtime.getRuntime();
		
		logger.info("执行脚本:{}",command);
		
		try {
			Process process = runtime.exec(cmd);
			
			logger.info("启动脚本");
			
			/*BufferedReader msgbr = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String msg = msgbr.readLine();
			while(EmptyUtil.isNotEmpty(msg)) {
				logger.debug(msg);
				msg = msgbr.readLine();
			}
			
			BufferedReader errorbr = new BufferedReader(new InputStreamReader(process.getErrorStream()));
			String errormsg = errorbr.readLine();
			while(EmptyUtil.isNotEmpty(errormsg)) {
				logger.info(errormsg);
				if(errormsg.contains("ERROR")||errormsg.contains("error")) {
					return "ERROR:"+errormsg;
				}
				errormsg = errorbr.readLine();
			}
			
			errorbr.close();
			msgbr.close();
			
			process.waitFor();
			
			process.destroy();*/
			
			process.getOutputStream().close();
			Scanner sc = new Scanner(process.getInputStream());
			
			while(sc.hasNext()) {
				String msg = sc.next();
				logger.debug(msg);
				if(msg.contains("ERROR")||msg.contains("error")) {
					return "ERROR:"+msg;
				}
			}
			
			logger.info("命令执行结束");
			
		} catch (Exception e) {
			logger.error("执行命令失败",e);
			return "ERROR:执行命令失败";
		}
		
		
		return "SUCCESS:执行完成";
	}
	public static void main(String[] args) throws IOException {
		executeCommand("wmic cpu get ProcessorId");
		 /*Process process = Runtime.getRuntime().exec(new String[]{"wmic", "cpu", "get", "ProcessorId"});
		 process.getOutputStream().close();
		 Scanner sc = new Scanner(process.getInputStream());
		 String property = sc.next();
		 String serial = sc.next();
		 System.out.println(property + ": " + serial);*/
	}
}
